#  Replication code for figures, tables, and reported quantities for
#  "The Limited Value of a Second Opinions"
#  William Minozzi and Jonathan Woon
#  2019/06/06

# Setup environment ----
suppressPackageStartupMessages({
  library(data.table)
  library(cowplot)
  library(rstan)
  library(rstanarm)
  library(extrafont)
  library(Cairo)
})
load("results/data.RData")
rstan_options(auto_write = TRUE)
options(mc.cores = parallel::detectCores())
loadfonts(quiet = TRUE)
set.seed(360222565)
theme_set(theme_minimal() + theme(
  strip.background = element_rect(
    fill = alpha("white", 0.0),
    color = alpha("white", 0.0)),
  axis.title = element_text(size = 10),
  axis.text = element_text(size = 8),
  axis.ticks.x = element_blank(),
  panel.border = element_rect(color = "black", size = .2, fill = NA),
  plot.title = element_text(hjust = 0.5),
  text = element_text(family = "Linux Libertine"),
  strip.text = element_text(size = 10),
  legend.position = "none"))

# Figures ----
#   Figure 2 (figure-equilibrium.pdf) ----
Eqm_Messages <- data.table(
  xmin = c(-100, -80, -100, -80, 20),
  xmax = c( -80, 100,  -80, 100, 100),
  ymin = c(-100, -80, -100, -80, 20),
  ymax = c( -80, 100,  -80, 100, 100),
  Treatment = factor(
    c("Single", "Single", "Aligned", "Aligned", "Opposed"),
    levels = c("Single", "Aligned", "Opposed")))
Eqm_Actions <- data.table(
  x    = c(-100,  20, -100, -80, -100, -80),
  xend = c(  20, 100,  -80, 100,  -80, 100),
  y    = c(-100,  60,  -90,  10,  -90,  10),
  yend = c(  20,  60,  -90,  10,  -90,  10),
  Treatment = factor(
    c("Opposed", "Opposed", "Single", "Single", "Aligned", "Aligned"),
    levels = c("Single", "Aligned", "Opposed")))

g <- ggplot(Eqm_Messages) +
  geom_rect(aes(ymax = ymax, ymin = ymin, xmax = xmax, xmin = xmin),
    alpha = .4) +
  facet_grid(. ~ Treatment) +
  geom_segment(data = Eqm_Actions,
    aes(x = x, xend = xend, y = y, yend = yend)) +
  scale_x_continuous("Target", breaks = c(-50, 0, 50)) +
  scale_y_continuous("Messages & Actions", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE)

cairo_pdf("results/figure-equilibrium.pdf",
  width = 6.5, height = 3)
suppressWarnings(cowplot::ggdraw() +
    cowplot::draw_plot(g, x = 0, y = 0, w = 1, h = .9) +
    cowplot::draw_label(
      paste0("Equilibrium Strategies"),
      size = 18, x = .5, y = .92,
      fontface = "bold",
      fontfamily = theme_get()$text[["family"]]) +
    theme_nothing())
dev.off()

#   Figure 3 (figure-targets-actions.pdf) ----
load(file = "results/equilibrium_action_models.RData")
cols <- c("blue", "purple")
Eqm_Messages <- data.table(
  xmin = c(-100, -80, -100, -80, 20), xmax = c( -80, 100,  -80, 100, 100),
  ymin = c(-100, -80, -100, -80, 20), ymax = c( -80, 100,  -80, 100, 100),
  Treatment = factor(c("Single", "Single", "Aligned", "Aligned", "Opposed"),
    levels = c("Single", "Aligned", "Opposed")))
Eqm_Actions <- data.table(
  x = c(-100, 20, -100, -80, -100, -80), xend = c(20, 100, -80, 100, -80, 100),
  y = c(-100, 60, -90, 10, -90, 10), yend = c(20, 60, -90, 10, -90, 10),
  Treatment = factor(
    c("Opposed", "Opposed", "Single", "Single", "Aligned", "Aligned"),
    levels = c("Single", "Aligned", "Opposed")))
b <- fixef(equilibrium_action_models[[1]])
reg_data <- data.table(
  Treatment = factor("Single", levels = c("Single", "Aligned", "Opposed")),
  x = -100, xend = -80, y = b[1] + b[3] + (b[2] + b[4]) * -100,
  yend = b[1] + b[3] + (b[2] + b[4]) * -80)
reg_data <- rbind(reg_data, data.table(
  Treatment = factor("Single", levels = c("Single", "Aligned", "Opposed")),
  x = -80, xend = 100, y = b[1] + b[2] * -80, yend = b[1] + b[2] * 190))
b <- fixef(equilibrium_action_models[[2]])
reg_data <- rbind(reg_data, data.table(
  Treatment = factor("Aligned", levels = c("Single", "Aligned", "Opposed")),
  x = -100, xend = -80, y = b[1] + b[3] + (b[2] + b[4]) * -100,
  yend = b[1] + b[3] + (b[2] + b[4]) * -80))
reg_data <- rbind(reg_data, data.table(
  Treatment = factor("Aligned", levels = c("Single", "Aligned", "Opposed")),
  x = -80, xend = 100, y = b[1] + b[2] * -80, yend = b[1] + b[2] * 100))
b <- fixef(equilibrium_action_models[[3]])
reg_data <- rbind(reg_data, data.table(
  Treatment = factor("Opposed", levels = c("Single", "Aligned", "Opposed")),
  x = -100, xend = 20, y = b[1] + b[3] + (b[2] + b[4]) * -100,
  yend = b[1] + b[3] + (b[2] + b[4]) * 20))
reg_data <- rbind(reg_data, data.table(
  Treatment = factor("Opposed", levels = c("Single", "Aligned", "Opposed")),
  x = 20, xend = 100, y = b[1] + b[2] * 20, yend = b[1] + b[2] * 100))
g <- ggplot(data = Action_Data) +
  geom_segment(data = Eqm_Actions,
    aes(x = x, xend = xend, y = y, yend = yend), linetype = 2) +
  geom_point(aes(Target, Action), alpha = .1, size = .5, color = cols[1]) +
  geom_segment(data = reg_data, aes(x = x, xend = xend, y = y, yend = yend),
    color = cols[2], size = 1) +
  facet_grid(. ~ Treatment) +
  scale_x_continuous("Target", breaks = c(-50, 0, 50)) +
  scale_y_continuous("Action", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE)
cairo_pdf("results/figure-targets-actions.pdf",
  width = 6.5, height = 3.5)
suppressWarnings(cowplot::ggdraw() +
    cowplot::draw_plot(g, x = 0, y = 0, width = .97, height = .85) +
    cowplot::draw_label(
      paste0("Receivers Do Not Condition on Partition Strategies"),
      size = 18, x = .5, y = .875,
      fontface = "bold",
      fontfamily = theme_get()$text[["family"]]) +
    theme_nothing())
dev.off()

#   Figure 4 (figure-subject-level-message-strategies.pdf) ----
load(file = "results/sf_messages.RData")
md <- copy(Message_Data)
setDT(md)
setorder(md, ID)
md[, Message_Midpoint := (Message_Min + Message_Max) / 2]
md[Message_Midpoint == 0, Max_N_Messages := 201]
md[Message_Midpoint > 0, Max_N_Messages := 1 + 2 * (100 - Message_Midpoint)]
md[Message_Midpoint < 0, Max_N_Messages := 1 + 2 * (100 + Message_Midpoint)]
md[, Message_Range_Size := Message_Max - Message_Min]
md[Message_Midpoint == 0, Max_Message_Range_Size := 200]
md[Message_Midpoint > 0,
  Max_Message_Range_Size := 2 * (100 - Message_Midpoint)]
md[Message_Midpoint < 0,
  Max_Message_Range_Size := 2 * (100 + Message_Midpoint)]
md[, id := as.numeric(factor(ID))]
md_1 <- md[!Message_Midpoint %in% c(100, -100) & N_Messages != Max_N_Messages]
md_2 <- md[!Message_Midpoint %in% c(100, -100) & N_Messages == Max_N_Messages]
md_3 <- md[Message_Midpoint == 100]
md_4 <- md[Message_Midpoint == -100]
dl_messages <- list(
  N_id = max(md$id),
  N_period  = max(md$Period),
  N_1 = nrow(md_1),
  id_1 = md_1$id,
  period_1 = md_1$Period,
  Target_1 = md_1$Target / 100,
  Message_Midpoint_1 = md_1$Message_Midpoint / 100,
  log_Message_Range_Size_1 = log1p(md_1$Message_Range_Size / 100),
  N_2 = nrow(md_2),
  id_2 = md_2$id,
  period_2 = md_2$Period,
  Target_2 = md_2$Target / 100,
  Message_Midpoint_2 = md_2$Message_Midpoint / 100,
  log_Max_Message_Range_Size_2 = log1p(md_2$Max_Message_Range_Size / 100),
  N_3 = nrow(md_3),
  id_3 = md_3$id,
  period_3 = md_3$Period,
  Target_3 = md_3$Target / 100,
  U = 1,
  N_4 = nrow(md_4),
  id_4 = md_4$id,
  period_4 = md_4$Period,
  Target_4 = md_4$Target / 100,
  L = -1)
ex_messages <- extract(sf_messages)
sim_messages_id <- CJ(
  id = seq_len(dl_messages$N_id),
  sim = seq_len(4000))
sim_messages_id[, `:=`(
  a = as.vector(ex_messages$a_id),
  b = as.vector(ex_messages$b_id),
  g = as.vector(ex_messages$g_id),
  h = as.vector(ex_messages$h_id))]
sim_messages_id_summary <- sim_messages_id[,
  .(a = median(a), b = median(b), g = median(g), h = median(h)), id]
ggdf_messages <- CJ(id = seq_len(dl_messages$N_id),
  x = seq(-1, 1, length.out = 80))
ggdf_messages <- merge(ggdf_messages, sim_messages_id_summary, by = "id")
ggdf_messages[, Message := 100 * pmin(pmax(-1, a + b * x), 1)]
ggdf_messages[Message == 0,
  n_messages := pmax(1, pmin(g + h * x, 200))]
ggdf_messages[Message > 0,
  n_messages := pmin(pmax(1, pmin(g + h * x, 200)), 1 + 2 * (1 - Message))]
ggdf_messages[Message < 0,
  n_messages := pmin(pmax(1, pmin(g + h * x, 200)), 1 + 2 * (1 + Message))]
ggdf_messages[, `:=`(
  message_min = pmin(100, pmax(-100, Message - n_messages / 2)),
  message_max = pmin(100, pmax(-100, Message + n_messages / 2)),
  Sender_Type = Sender_Data$Sender_Type[id],
  Target = x * 100
)]
ggdf_messages[, Treatment := "Single"]
ggdf_messages[Sender_Type %like% "Aligned", Treatment := "Aligned"]
ggdf_messages[Sender_Type %like% "Opposed", Treatment := "Opposed"]
ggdf_messages[, Bias := "Moderate"]
ggdf_messages[Sender_Type %like% "Extremist", Bias := "Extremist"]
ggdf_messages[, Treatment := factor(Treatment,
  levels = c("Single", "Aligned", "Opposed"))]
ggdf_messages[, Bias := factor(Bias, levels = c("Moderate", "Extremist"))]
ggdf_messages[, id := factor(id)]
cols <- c("blue", "purple")
g1 <- ggplot(ggdf_messages[Treatment == "Single"], aes(Target, Message)) +
  geom_abline(intercept = 0, slope = 1, color = "gray92") +
  geom_point(data = md[Treatment == "Single"],
    aes(x = Target, y = Message_Midpoint), alpha = .05, color = cols[1]) +
  geom_line(aes(group = id), size = .1, alpha = .25, color = cols[1]) +
  geom_smooth(se = FALSE, method = "lm", color = cols[2]) +
  facet_grid(Bias  ~ Treatment) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", limits = c(-100, 100), breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE) +
  theme(strip.text.y = element_text(color = alpha("white", 0.0)))
g2 <- ggplot(ggdf_messages[Treatment == "Aligned" & Bias == "Moderate"],
  aes(Target, Message)) +
  geom_abline(intercept = 0, slope = 1, color = "gray92") +
  geom_point(data = md[Treatment == "Aligned" & Bias == "Moderate"],
    aes(x = Target, y = Message_Midpoint), alpha = .05, color = cols[1]) +
  geom_line(aes(group = id), size = .1, alpha = .25, color = cols[1]) +
  geom_smooth(se = FALSE, method = "lm", color = cols[2]) +
  facet_grid(Bias  ~ Treatment) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", limits = c(-100, 100), breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE) +
  theme(
    axis.text = element_text(color = alpha("white", 0.0)),
    strip.text.y = element_text(color = alpha("white", 0.0)))
g3 <- ggplot(ggdf_messages[Treatment == "Opposed" & Bias == "Moderate"],
  aes(Target, Message)) +
  geom_abline(intercept = 0, slope = 1, color = "gray92") +
  geom_point(data = md[Treatment == "Opposed" & Bias == "Moderate"],
    aes(x = Target, y = Message_Midpoint), alpha = .05, color = cols[1]) +
  geom_line(aes(group = id), size = .1, alpha = .25, color = cols[1]) +
  geom_smooth(se = FALSE, method = "lm", color = cols[2]) +
  facet_grid(Bias  ~ Treatment) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", limits = c(-100, 100), breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE) +
  theme(axis.text = element_text(color = alpha("white", 0.0)))
g4 <- ggplot(ggdf_messages[Treatment == "Aligned" & Bias == "Extremist"],
  aes(Target, Message)) +
  geom_abline(intercept = 0, slope = 1, color = "gray92") +
  geom_point(data = md[Treatment == "Aligned" & Bias == "Extremist"],
    aes(x = Target, y = Message_Midpoint), alpha = .05, color = cols[1]) +
  geom_line(aes(group = id), size = .1, alpha = .25, color = cols[1]) +
  geom_smooth(se = FALSE, method = "lm", color = cols[2]) +
  facet_grid(Bias  ~ Treatment) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", limits = c(-100, 100), breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE) +
  theme(strip.text = element_text(color = alpha("white", 0.0)))
g5 <- ggplot(ggdf_messages[Treatment == "Opposed" & Bias == "Extremist"],
  aes(Target, Message)) +
  geom_abline(intercept = 0, slope = 1, color = "gray92") +
  geom_point(data = md[Treatment == "Opposed" & Bias == "Extremist"],
    aes(x = Target, y = Message_Midpoint), alpha = .05, color = cols[1]) +
  geom_line(aes(group = id), size = .1, alpha = .25, color = cols[1]) +
  geom_smooth(se = FALSE, method = "lm", color = cols[2]) +
  facet_grid(Bias  ~ Treatment) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", limits = c(-100, 100), breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE) +
  theme(
    axis.text.y = element_text(color = alpha("white", 0.0)),
    strip.text.x = element_text(color = alpha("white", 0.0)))
hm <- -.02 # horizontal margin
vm <- -.05 # vertical margin
hp <- -.15 # horizontal padding between facets
vp <- -.12 # vertical padding between facets
ts <- .15 # title space
bs <- .05 # title space
fw <- (1 - 2 * hp - 2 * hm) / 3  # facet width
fh <- (1 - vp - 2 * vm - ts - bs) / 2  # facet height
cairo_pdf("results/figure-subject-level-message-strategies.pdf",
  width = 6.5, height = 5)
suppressWarnings(cowplot::ggdraw() +
    cowplot::draw_plot(g1, x = hm, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g2, x = hm + fw + hp, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g3, x = hm + 2 * fw + 2 * hp, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g4, x = hm + fw + hp, y = bs + vm,
      width = fw, height = fh) +
    cowplot::draw_plot(g5, x = hm + 2 * fw + 2 * hp, y = bs + vm,
      width = fw, height = fh) +
    cowplot::draw_label(
      paste0("Senders Naïvely Exaggerate"),
      size = 18, x = .5, y = bs + vm + vp + 2 * fh + ts / 4,
      fontface = "bold",
      fontfamily = theme_get()$text[["family"]]) +
    cowplot::draw_label(
      paste0("Target"),
      size = 10, x = .5, y = bs * 2 / 3,
      fontfamily = theme_get()$text[["family"]]) +
    cowplot::draw_label(
      paste0("Message Midpoint"),
      size = 10, x = .03, y = .5, angle = 90,
      fontfamily = theme_get()$text[["family"]]) +
    theme_nothing())
dev.off()

#   Figure 5 (figure-one-parameter.pdf) ----
calc_prediction_error <- function(e, x, m) {
  pred_m <- ifelse(x + e > 100, 100, ifelse(x + e < -100, -100, x + e))
  mean((m - pred_m) ^ 2) ^ .5
}
predicted_exaggeration <- Message_Data[, .(
  pred_e = optim(0, calc_prediction_error, x = Target, m = Message,
    method = "Brent", lower = -100, upper = 100)$par,
  rmse = optim(0, calc_prediction_error, x = Target, m = Message,
    method = "Brent", lower = -100, upper = 100)$value),
  .(Treatment, Session, Bias, ID)]
g <- ggplot(predicted_exaggeration) +
  geom_density(aes(x = pred_e, group = Bias, fill = Bias), alpha = .2,
    bw = 6, color = NA) +
  xlab("Distribution of Estimated Exaggeration Parameters") +
  ylab("Kernel Densities") +
  facet_grid(Treatment ~ ., scales = "free_y") +
  theme(axis.text.y = element_blank(),
    legend.position = "none") +
  scale_x_continuous(limits = c(-100, 100), expand = c(0, 0)) +
  scale_y_continuous(limits = c(0, NA), expand = c(0, 0)) +
  ggtitle("Estimates of Naïve Exaggeration")
y1 <- with(subset(ggplot_build(g)$data[[1]], PANEL == 1), range(y))
y2 <- with(subset(ggplot_build(g)$data[[1]], PANEL == 2), range(y))
y3 <- with(subset(ggplot_build(g)$data[[1]], PANEL == 3), range(y))
g <- g + geom_segment(data = data.table(
  x =    c(   40, 40, 80, 40, -80),
  xend = c(   40, 40, 80, 40, -80),
  y =    c(y1[1], y2[1], y2[1], y3[1], y3[1]),
  yend = c(y1[2], y2[2], y2[2], y3[2], y3[2]),
  Treatment = factor(c("Single", "Aligned", "Aligned", "Opposed", "Opposed"),
    levels = c("Single", "Aligned", "Opposed")),
  Bias = c("Moderate", "Moderate", "Extremist", "Moderate", "Extremist")),
  aes(x = x, xend = xend, y = y, yend = yend),
  linetype = 3, color = "gray72")
ann_text <- data.table(x = 60, y = .015,
  Treatment = factor("Single",
    levels = c("Single", "Aligned", "Opposed")))
g <- g + geom_text(data = ann_text, aes(x = x, y = y), label = "Moderate",
  family = "Linux Libertine")
ann_text <- data.table(x = 82, y = .015,
  Treatment = factor(c("Aligned"),
    levels = c("Single", "Aligned", "Opposed")))
g <- g + geom_text(data = ann_text, aes(x = x, y = y), label = "Extremist",
  family = "Linux Libertine")
ann_text <- data.table(x = 40, y = .034,
  Treatment = factor(c("Aligned"),
    levels = c("Single", "Aligned", "Opposed")))
g <- g + geom_text(data = ann_text, aes(x = x, y = y), label = "Moderate",
  family = "Linux Libertine")
ann_text <- data.table(x = 55, y = .015,
  Treatment = factor(c("Opposed"),
    levels = c("Single", "Aligned", "Opposed")))
g <- g + geom_text(data = ann_text, aes(x = x, y = y), label = "Moderate",
  family = "Linux Libertine")
ann_text <- data.table(x = -80, y = .024,
  Treatment = factor(c("Opposed"),
    levels = c("Single", "Aligned", "Opposed")))
g <- g + geom_text(data = ann_text, aes(x = x, y = y), label = "Extremist",
  family = "Linux Libertine")
cairo_pdf("results/figure-one-parameter.pdf", width = 4.8, height = 6.5)
print(g)
dev.off()

set.seed(198273)
Matching::ks.boot(
  predicted_exaggeration[Treatment == "Single", pred_e],
  predicted_exaggeration[Treatment == "Opposed" & Bias == "Moderate", pred_e],
  nboots = 1000)

Matching::ks.boot(
  predicted_exaggeration[Treatment == "Single", pred_e],
  predicted_exaggeration[Treatment == "Aligned" & Bias == "Moderate", pred_e],
  nboots = 1000)

Matching::ks.boot(
  predicted_exaggeration[Treatment == "Opposed" & Bias == "Moderate", pred_e],
  predicted_exaggeration[Treatment == "Aligned" & Bias == "Moderate", pred_e],
  nboots = 1000)

#   Figure 6 (figure-message-ranges-actions) ----
cols <- c("blue", "purple")
g1 <- ggplot(Message_Data[Treatment == "Single"], aes(Message, Action)) +
  geom_segment(aes(x = -100, xend = 100, y = -100, yend = 100), size = .1,
    color = "grey92") +
  geom_point(color = cols[1], alpha = .15, size = .5) +
  geom_smooth(method = "loess", se = FALSE, color = cols[2], span = 10) +
  facet_grid(Bias ~ Treatment) +
  theme(strip.text.y = element_text(color = alpha("white", 0.0))) +
  scale_x_continuous(" ", breaks = c(-50, 0, 50)) +
  scale_y_continuous(" ", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE, xlim = c(-100, 100))
g2 <- ggplot(Message_Data[Treatment == "Aligned" & Bias == "Moderate"],
  aes(Message, Action)) +
  geom_segment(aes(x = -100, xend = 100, y = -100, yend = 100), size = .1,
    color = "grey92") +
  geom_point(color = cols[1], alpha = .15, size = .5) +
  geom_smooth(method = "loess", se = FALSE, color = cols[2], span = 10) +
  facet_grid(Bias ~ Treatment) +
  theme(
    strip.text.y = element_text(color = alpha("white", 0.0)),
    axis.text = element_text(color = alpha("white", 0.0))) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE, xlim = c(-100, 100))
g3 <- ggplot(Message_Data[Treatment == "Opposed" & Bias == "Moderate"],
  aes(Message, Action)) +
  geom_segment(aes(x = -100, xend = 100, y = -100, yend = 100), size = .1,
    color = "grey92") +
  geom_point(color = cols[1], alpha = .15, size = .5) +
  geom_smooth(method = "loess", se = FALSE, color = cols[2], span = 10) +
  facet_grid(Bias ~ Treatment) +
  theme(axis.text = element_text(color = alpha("white", 0.0))) +
  scale_x_continuous("", breaks = c(-50, 0, 50)) +
  scale_y_continuous("", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE, xlim = c(-100, 100))
g4 <- ggplot(Message_Data[Treatment == "Aligned" & Bias == "Extremist"],
  aes(Message, Action)) +
  geom_segment(aes(x = -100, xend = 100, y = -100, yend = 100), size = .1,
    color = "grey92") +
  geom_point(color = cols[1], alpha = .15, size = .5) +
  geom_smooth(method = "loess", se = FALSE, color = cols[2], span = 10) +
  facet_grid(Bias ~ Treatment) +
  theme(strip.text = element_text(color = alpha("white", 0.0))) +
  scale_x_continuous(" ", breaks = c(-50, 0, 50)) +
  scale_y_continuous(" ", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE, xlim = c(-100, 100))
g5 <- ggplot(Message_Data[Treatment == "Opposed" & Bias == "Extremist"],
  aes(Message, Action)) +
  geom_segment(aes(x = -100, xend = 100, y = -100, yend = 100), size = .1,
    color = "grey92") +
  geom_point(color = cols[1], alpha = .15, size = .5) +
  geom_smooth(method = "loess", se = FALSE, color = cols[2], span = 10) +
  facet_grid(Bias ~ Treatment) +
  theme(
    strip.text.x = element_text(color = alpha("white", 0.0)),
    axis.text.y = element_text(color = alpha("white", 0.0))) +
  scale_x_continuous(" ", breaks = c(-50, 0, 50)) +
  scale_y_continuous(" ", breaks = c(-50, 0, 50)) +
  coord_fixed(ratio = 1, expand = FALSE, xlim = c(-100, 100))
hm <- -.02 # horizontal margin
vm <- -.05 # vertical margin
hp <- -.15 # horizontal padding between facets
vp <- -.12 # vertical padding between facets
ts <- .15 # title space
bs <- .05 # title space
fw <- (1 - 2 * hp - 2 * hm) / 3  # facet width
fh <- (1 - vp - 2 * vm - ts - bs) / 2  # facet height
cairo_pdf("results/figure-message-ranges-actions.pdf", width = 6.5, height = 5)
suppressWarnings(cowplot::ggdraw() +
    cowplot::draw_plot(g1, x = hm, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g2, x = hm + fw + hp, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g3, x = hm + 2 * fw + 2 * hp, y = bs + vm + vp + fh,
      width = fw, height = fh) +
    cowplot::draw_plot(g4, x = hm + fw + hp, y = bs + vm,
      width = fw, height = fh) +
    cowplot::draw_plot(g5, x = hm + 2 * fw + 2 * hp, y = bs + vm,
      width = fw, height = fh) +
    cowplot::draw_label(
      paste0("Receivers Invert Messages"),
      size = 18, x = .5, y = bs + vm + vp + 2 * fh + ts / 4,
      fontface = "bold",
      fontfamily = theme_get()$text[["family"]]) +
    cowplot::draw_label(
      paste0("Message"),
      size = 10, x = .5, y = bs * 2 / 3,
      fontfamily = theme_get()$text[["family"]]) +
    cowplot::draw_label(
      paste0("Action"),
      size = 10, x = .03, y = .5, angle = 90,
      fontfamily = theme_get()$text[["family"]]) +
    theme_nothing())
dev.off()

#   Figure 7 (figure-behavioral-receiver.pdf) ----
ad <- copy(Action_Data)
calc_prediction_error <- function(e, m, a) {
  pred_a <- ifelse(m > -100 + e, m - e, -100)
  mean((a - pred_a) ^ 2) ^ .5
}
predicted_exaggeration1 <- ad[Single == 1, .(
  e1 = NA_real_,
  e2 = optim(0, calc_prediction_error, m = Moderate_Message, a = Action,
    method = "Brent", lower = -200, upper = 200)$par,
  e3 = 1,
  rmse = optim(0, calc_prediction_error, m = Moderate_Message,
    a = Action, method = "Brent", lower = -200, upper = 200)$value),
  .(Treatment, Session, ID)]
calc_prediction_error <- function(e, m1, m2, a) {
  pred_a1 <- m1 - e[1]
  pred_a2 <- m2 - e[2]
  pred_a1 <- pmin(100, pmax(-100, pred_a1))
  pred_a2 <- pmin(100, pmax(-100, pred_a2))
  pred_a <- e[3] * pred_a1 + (1 - e[3]) * pred_a2
  pred_a <- pmin(100, pmax(-100, pred_a))
  mean((a - pred_a) ^ 2) ^ .5
}
predicted_exaggeration2 <- rbind(predicted_exaggeration1,
  ad[Treatment == "Aligned", .(
    e1 = optim(c(80, 40, 0.5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[1],
    e2 = optim(c(80, 40, .5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[2],
    e3 = optim(c(80, 40, .5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[3],
    rmse = optim(c(80, 40, 0.5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$value),
    .(Treatment, Session, ID)])
predicted_exaggeration3 <- rbind(predicted_exaggeration2,
  ad[Treatment == "Opposed", .(
    e1 = optim(c(-80, 40, 0.5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[1],
    e2 = optim(c(-80, 40, .5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[2],
    e3 = optim(c(-80, 40, .5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$par[3],
    rmse = optim(c(-80, 40, 0.5), calc_prediction_error, m1 = Extremist_Message,
      m2 = Moderate_Message, a = Action)$value),
    .(Treatment, Session, ID)])
p1 <- ggplot(predicted_exaggeration3[Treatment == "Single"], aes(e2)) +
  geom_vline(xintercept = 40, linetype = 3, color = "gray72") +
  geom_density(alpha = .2, color = NA, fill = "gray52", bw = 6) +
  ylab("Density") + xlab("Moderate Deduction") +
  scale_x_continuous(breaks = c(-100, 0, 100), limits = c(-150, 150),
    expand = c(0, 0)) +
  scale_y_continuous(breaks = c(0, .01, .02), limits = c(0, .0255),
    expand = c(0, 0)) +
  theme(legend.position = "none",
    panel.grid.major = element_line(colour = "grey92"),
    panel.grid.minor = element_line(colour = "grey92", size = 0.25),
    plot.title = element_text(size = 12),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 12)) +
  ggtitle("Message Deductions—Single")
p2 <- ggplot(predicted_exaggeration3[Treatment != "Single"],
  aes(e3, fill = Treatment)) +
  geom_vline(xintercept = .5, linetype = 3, color = "gray72") +
  geom_density(aes(color = Treatment), alpha = .2) +
  scale_x_continuous(breaks = c(0, 0.5, 1), limits = c(0, 1),
    expand = c(0, 0), labels = c("0", "0.5", "1")) +
  scale_y_continuous(breaks = c(0, 2, 4), limits = c(0, 5), expand = c(0, 0)) +
  scale_color_manual(values = c("Aligned" = "black", "Opposed" = "grey92")) +
  ylab("Density") + xlab("Weight on Extremist Message") +
  theme(legend.position = "none",
    panel.grid.major = element_line(colour = "grey92"),
    panel.grid.minor = element_line(colour = "grey92", size = 0.25),
    plot.title = element_text(size = 12),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 12)) +
  annotate("text", x = .3, y = 2.2, label = "Aligned", hjust = 1,
    family = "Linux Libertine", size = 4) +
  annotate("text", x = .8, y = 2.4, label = "Opposed", hjust = 1,
    family = "Linux Libertine", size = 4) +
  ggtitle("Message Weights—Aligned & Opposed")
p3 <- ggplot(predicted_exaggeration3[Treatment == "Aligned"],
  aes(e2, e1, color = Treatment, group = Treatment)) +
  geom_vline(xintercept = 40, linetype = 3, color = "gray72") +
  geom_hline(yintercept = 80, linetype = 3, color = "gray72") +
  stat_density2d(aes(alpha = ..level..), h = c(60, 60), size = 1,
    contour = TRUE, color = "#F8766D") +
  coord_fixed(xlim = c(-150, 150), ylim = c(-150, 150), expand = FALSE) +
  scale_x_continuous(breaks = c(-100, 0, 100)) +
  scale_y_continuous(breaks = c(-100, 0, 100)) +
  xlab("Moderate Deduction") +
  ylab("Extremist Deduction") +
  scale_fill_gradient(low = "gray92", high = "#F8766D") +
  theme(legend.position = "none",
    panel.grid.major = element_line(colour = "grey92"),
    panel.grid.minor = element_line(colour = "grey92", size = 0.25),
    plot.title = element_text(size = 12),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 12)) +
  ggtitle("Message Deductions—Aligned")
p4 <- ggplot(predicted_exaggeration3[Treatment == "Opposed"], aes(e2, e1)) +
  geom_vline(xintercept = 40, linetype = 3, color = "gray72") +
  geom_hline(yintercept = -80, linetype = 3, color = "gray72") +
  stat_density2d(aes(alpha = ..level..), h = c(60, 60), size = 1,
    contour = TRUE, color = "#00BFC4") +
  coord_fixed(xlim = c(-150, 150), ylim = c(-150, 150), expand = FALSE) +
  scale_fill_gradient(low = "gray92", high = "#00BFC4") +
  scale_x_continuous(breaks = c(-100, 0, 100)) +
  scale_y_continuous(breaks = c(-100, 0, 100)) +
  xlab("Moderate Deduction") +
  ylab("Extremist Deduction") +
  theme(legend.position = "none",
    panel.grid.major = element_line(colour = "grey92"),
    panel.grid.minor = element_line(colour = "grey92", size = 0.25),
    plot.title = element_text(size = 12),
    axis.text = element_text(size = 8),
    axis.title = element_text(size = 12)) +
  ggtitle("Message Deductions—Opposed")
cairo_pdf("results/figure-behavioral-receiver.pdf", width = 12, height = 3)
suppressWarnings(cowplot::ggdraw() +
    draw_plot(p1, 0.0, 0.00, 1/4 - .01, 1) +
    draw_plot(p3, 1/4, 0.00, 1/4 - .01, 1) +
    draw_plot(p4, 2/4, 0.00, 1/4 - .01, 1) +
    draw_plot(p2, 3/4, 0.00, 1/4 - .01, 1))
dev.off()

# Tables ----
#   Table 1 (table-sessions.tex) ----
ad <- copy(All_Data)
ad[, Condition := ""]
real_session_numbers <- c(
  3, 4, 9, 10, 13, 18,
  1, 6, 8, 12, 15, 16,
  2, 5, 7, 11, 14, 17)
tab <- ad[, .(
  `\\# Subjects` = length(unique(ID)),
  `\\# Groups` = length(unique(Group)),
  `\\# Obs.` = 24 * length(unique(Group))),
  .(Condition, Session = as.character(real_session_numbers[Session]))]
tab2 <- cbind(data.table(Condition = "", Session = " "),
  rbind(colSums(tab[1:6, -(1:2)])))
tab3 <- cbind(data.table(Condition = "", Session = " "),
  rbind(colSums(tab[7:12, -(1:2)])))
tab4 <- cbind(data.table(Condition = "", Session = " "),
  rbind(colSums(tab[13:18, -(1:2)])))
tab5 <- cbind(data.table(Condition = "", Session = ""),
  rbind(colSums(tab[, -(1:2)])))
tab <- rbind(tab[1:6], tab2, tab[7:12], tab3, tab[13:18], tab4, tab5)
tab[Session == "3", Condition := "Single"]
tab[Session == "1", Condition := "Aligned"]
tab[Session == "2", Condition := "Opposed"]
tab[Session == "", Condition := "Total"]
tab[, lineend := "\\\\"]
tab[Session %in% c("13", "15", "14"), lineend := "\\\\ \\vspace{.2em}"]
tab[Session %in% c("18", "16", "17"), lineend := "\\\\ \\vspace{.8em}"]
tab[, index := .I]
tab <- tab[, paste(.SD, collapse = "&"), index][,
  paste(gsub("&\\\\", "\\\\", V1, fixed = TRUE),
    collapse = "\n")]
tab <- c(
  "\\begin{table}[t] \\footnotesize\n",
  "\\begin{center}\n",
  "\\caption{Session Details}\n",
  "\\label{tab:sessions} \\vspace{1em}\n",
  "\\begin{threeparttable}\n",
  "\\begin{tabular}{lcccc}  \\vspace{.1em}\n",
  "Condition & Session &\\# Subjects & \\# Groups & \\# Obs.\\\\  \\hline\n",
  tab, "\n",
  "\\hline\n",
  "\\end{tabular}\n",
  "\\begin{tablenotes}
  \\item{\\footnotesize
  Groups were randomly assigned every period.
  An observation is a single interaction between
  members of a group.
  There were 24 observations per group.
  }
  \\end{tablenotes}",
  "\\end{threeparttable}\n",
  "\\end{center}\n",
  "\\end{table}"
)
cat(tab, file = "results/table-sessions.tex")

#   Table 2 (table-partition-regression.tex) ----
cut_p <- function (x)  {
  x <- as.numeric(cut(x, breaks = c(0, 0.001, 0.01, 0.05),
    include.lowest = TRUE))
  x[is.na(x)] <- 4
  labels <- c("^{***}", "^{**}", "^*", " ")
  labels[x]
}
b1 <- fixef(equilibrium_action_models[[1]])
se1 <- diag(vcov(equilibrium_action_models[[1]])) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(equilibrium_action_models[[1]])) ^ .5,
  sigma(equilibrium_action_models[[1]]))
b2 <- fixef(equilibrium_action_models[[2]])
se2 <- diag(vcov(equilibrium_action_models[[2]])) ^ .5
z2 <- abs(b2 / se2)
p2 <- 2 * (1 - pnorm(z2))
sd2 <- c(unlist(VarCorr(equilibrium_action_models[[2]])) ^ .5,
  sigma(equilibrium_action_models[[2]]))
b3 <- fixef(equilibrium_action_models[[3]])
se3 <- diag(vcov(equilibrium_action_models[[3]])) ^ .5
z3 <- abs(b3 / se3)
p3 <- 2 * (1 - pnorm(z3))
sd3 <- c(unlist(VarCorr(equilibrium_action_models[[3]])) ^ .5,
  sigma(equilibrium_action_models[[3]]))
B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)
B2 <- paste0(sprintf("%.02f", b2), cut_p(p2))
S2 <- paste0("(", sprintf("%.02f", se2), ")")
SD2 <- sprintf("%.01f", sd2)
B3 <- paste0(sprintf("%.02f", b3), cut_p(p3))
S3 <- paste0("(", sprintf("%.02f", se3), ")")
SD3 <- sprintf("%.01f", sd3)
tab <- paste0("
  \\begin{table}[t] \\footnotesize
  \\begin{center}
  \\caption{Regressions of Action on Target and Partition}
  \\label{tab:partition-regression} \\vspace{1em}
  \\begin{threeparttable}
  \\begin{tabular}{lccc}  \\vspace{.1em}
  & Single      & Aligned    & Opposed \\\\
  \\hline
  Target                      &$", B1[2], "$&$", B2[2], "$&$", B3[2], "$\\\\
  &$", S1[2], "$&$", S2[2], "$&$", S3[2], "$\\\\
  Low Region                  &$", B1[3], "$&$", B2[3], "$&$", B3[3], "$\\\\
  &$", S1[3], "$&$", S2[3], "$&$", S3[3], "$\\\\
  Target $\\times$ Low Region            &$",
  B1[4], "$&$", B2[4], "$&$", B3[4], "$\\\\
  &$", S1[4], "$&$", S2[4], "$&$", S3[4], "$\\\\
  Intercept                   &$", B1[1], "$&$", B2[1], "$&$", B3[1], "$\\\\
  &$", S1[1], "$&$", S2[1], "$&$", S3[1], "$\\\\
  \\hline
  $n$ Observations            &$",
  nobs(equilibrium_action_models[[1]]), "$&$",
  nobs(equilibrium_action_models[[2]]), "$&$",
  nobs(equilibrium_action_models[[3]]), "$\\\\
  $n$ Subjects                &$",
  ngrps(equilibrium_action_models[[1]])[1], "$&$",
  ngrps(equilibrium_action_models[[2]])[1], "$&$",
  ngrps(equilibrium_action_models[[3]])[1], "$\\\\
  $n$ Sessions                &$",
  ngrps(equilibrium_action_models[[1]])[2], "$&$",
  ngrps(equilibrium_action_models[[2]])[2], "$&$",
  ngrps(equilibrium_action_models[[3]])[2], "$\\\\
  \\hline
  \\emph{Error terms} & \\multicolumn{3}{c}{\\underline{Group SD}}\\\\
  Subject                     &$", SD1[1], "$&$", SD2[1], "$&$", SD3[1], "$\\\\
  Session                     &$", SD1[2], "$&$", SD2[2], "$&$", SD3[2], "$\\\\
  Residual                    &$", SD1[3], "$&$", SD2[3], "$&$", SD3[3], "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the results of separate mixed effects models of
  \\emph{Actions} for each treatment condition.
  For the Single and Aligned models, the \\emph{High Partition} begins at
  \\emph{Target} $=-80$; for Opposed, it begins at \\emph{Target} $=20$.
  The model also includes random
  intercepts for Session and Subject to control for the panel structure of the
  data.
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
  }
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-partition-regression.tex")

#   Table 3 (table-payoff-model.tex) ----
load(file = "results/payoff-models.RData")
b1 <- fixef(payoff_model)
se1 <- diag(vcov(payoff_model)) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(payoff_model)) ^ .5, sigma(payoff_model))
b2 <- fixef(payoff_period_model)
se2 <- diag(vcov(payoff_period_model)) ^ .5
z2 <- abs(b2 / se2)
p2 <- 2 * (1 - pnorm(z2))
sd2 <- c(unlist(VarCorr(payoff_period_model)) ^ .5, sigma(payoff_period_model))
B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)
B2 <- paste0(sprintf("%.02f", b2), cut_p(p2))
S2 <- paste0("(", sprintf("%.02f", se2), ")")
SD2 <- sprintf("%.01f", sd2)
tab <- paste0("
  \\begin{table}[t] \\footnotesize
  \\begin{center}
  \\caption{Regression of Payoffs on Treatment}
  \\label{tab:payoff-model} \\vspace{1em}
  \\begin{threeparttable}
  \\begin{tabular}{lcc}  \\vspace{.1em}
  & [1]      & [2] \\\\
  \\hline
  Aligned                &$", B1[2], "$&$", B2[2], "$\\\\
  &$", S1[2], "$&$", S2[2], "$\\\\
  Opposed                &$", B1[3], "$&$", B2[3], "$\\\\
  &$", S1[3], "$&$", S2[3], "$\\\\
  Aligned $\\times$ Second Half     &$           $&$", B2[5], "$\\\\
  &$           $&$", S2[5], "$\\\\
  Opposed $\\times$ Second Half     &$           $&$", B2[6], "$\\\\
  &$           $&$", S2[6], "$\\\\
  Second Half              &$           $&$", B2[4], "$\\\\
  &$           $&$", S2[4], "$\\\\
  Intercept              &$", B1[1], "$&$", B2[1], "$\\\\
  &$", S1[1], "$&$", S2[1], "$\\\\
  \\hline
  $n$ Observations  &$", nobs(payoff_model), "$\\\\
  $n$ Subjects      &$", ngrps(payoff_model)[1], "$\\\\
  $n$ Sessions      &$", ngrps(payoff_model)[2], "$\\\\
  \\hline
  \\emph{Error terms}& \\multicolumn{2}{c}{\\underline{Group SD}}\\\\
  Subject           &$", SD1[1], "$&$", SD2[1], "$\\\\
  Session           &$", SD1[2], "$&$", SD2[2], "$\\\\
  Residual          &$", SD1[3], "$&$", SD2[3], "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the results of a mixed effects model of Payoffs
  on Treatment conditions, with the
  Single condition as the excluded category.
  Points were calculated as in the experiment
  ($320 - |\\text{Target} - \\text{Action}|$), and then converted to US Dollars
  at the rate used in the experimental sessions.
  The model also includes random
  intercepts for Session and Subject to control for the panel structure of the
  data.\\\\
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
  }
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-payoff-model.tex")

#   Table 4 (table-width-model.tex) ----
load(file = "results/width-model.RData")
b1 <- fixef(width_model)
se1 <- diag(vcov(width_model)) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(width_model)) ^ .5, sigma(width_model))
B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)
tab <- paste0("
  \\begin{table}[t] \\footnotesize
  \\begin{center}
  \\caption{Regression of Width of the Message Interval on Treatment/Type}
  \\label{tab:width-model} \\vspace{1em}
  \\begin{threeparttable}
  \\begin{tabular}{lc}  \\vspace{.1em}
  & [1]      \\\\
  \\hline
  Moderate/Aligned  &$", B1[2], "$\\\\
  &$", S1[2], "$\\\\
  Extremist/Aligned &$", B1[3], "$\\\\
  &$", S1[3], "$\\\\
  Moderate/Opposed  &$", B1[4], "$\\\\
  &$", S1[4], "$\\\\
  Extremist/Opposed &$", B1[5], "$\\\\
  &$", S1[5], "$\\\\
  Intercept         &$", B1[1], "$\\\\
  &$", S1[1], "$\\\\
  \\hline
  $n$ Observations  &$", nobs(width_model), "$\\\\
  $n$ Subjects      &$", ngrps(width_model)[1], "$\\\\
  $n$ Sessions      &$", ngrps(width_model)[2], "$\\\\
  \\hline
  \\emph{Error terms}&\\underline{Group SD}  \\\\
  Subject           &$", SD1[1], "$\\\\
  Session           &$", SD1[2], "$\\\\
  Residual          &$", SD1[3], "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the results of a mixed effects model of the Width of the
  Message Interval (Maximum Message - Minimium Message)
  on the interaction of Treatment conditions and Sender types,
  with the Moderate in the Single condition as the excluded category.
  The model also includes random intercepts for
  Session and Subject to control for the panel structure of the data.
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
  }
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-width-model.tex")

#   Table 5 (table-seq-message-model.tex) ----
load(file = "results/seq-message-models.RData")
b1 <- fixef(seq_message_aligned_model)
se1 <- diag(vcov(seq_message_aligned_model)) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(seq_message_aligned_model)) ^ .5,
  sigma(seq_message_aligned_model))

b2 <- fixef(seq_message_opposed_model)
se2 <- diag(vcov(seq_message_opposed_model)) ^ .5
z2 <- abs(b2 / se2)
p2 <- 2 * (1 - pnorm(z2))
sd2 <- c(unlist(VarCorr(seq_message_opposed_model)) ^ .5,
  sigma(seq_message_opposed_model))

b3 <- fixef(seq_message_joint_model)
se3 <- diag(vcov(seq_message_joint_model)) ^ .5
z3 <- abs(b3 / se3)
p3 <- 2 * (1 - pnorm(z3))
sd3 <- c(unlist(VarCorr(seq_message_joint_model)) ^ .5,
  sigma(seq_message_joint_model))

b4 <- fixef(seq_message_aligned_hi_model)
se4 <- diag(vcov(seq_message_aligned_hi_model)) ^ .5
z4 <- abs(b4 / se4)
p4 <- 2 * (1 - pnorm(z4))
sd4 <- c(unlist(VarCorr(seq_message_aligned_hi_model)) ^ .5,
  sigma(seq_message_aligned_hi_model))

b5 <- fixef(seq_message_opposed_lo_model)
se5 <- diag(vcov(seq_message_opposed_lo_model)) ^ .5
z5 <- abs(b5 / se5)
p5 <- 2 * (1 - pnorm(z5))
sd5 <- c(unlist(VarCorr(seq_message_opposed_lo_model)) ^ .5,
  sigma(seq_message_opposed_lo_model))

b6 <- fixef(seq_message_opposed_hi_model)
se6 <- diag(vcov(seq_message_opposed_hi_model)) ^ .5
z6 <- abs(b6 / se6)
p6 <- 2 * (1 - pnorm(z6))
sd6 <- c(unlist(VarCorr(seq_message_opposed_hi_model)) ^ .5,
  sigma(seq_message_opposed_hi_model))

B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)

B2 <- paste0(sprintf("%.02f", b2), cut_p(p2))
S2 <- paste0("(", sprintf("%.02f", se2), ")")
SD2 <- sprintf("%.01f", sd2)

B3 <- paste0(sprintf("%.02f", b3), cut_p(p3))
S3 <- paste0("(", sprintf("%.02f", se3), ")")
SD3 <- sprintf("%.01f", sd3)


B4 <- paste0(sprintf("%.02f", b4), cut_p(p4))
S4 <- paste0("(", sprintf("%.02f", se4), ")")
SD4 <- sprintf("%.01f", sd4)

B5 <- paste0(sprintf("%.02f", b5), cut_p(p5))
S5 <- paste0("(", sprintf("%.02f", se5), ")")
SD5 <- sprintf("%.01f", sd5)

B6 <- paste0(sprintf("%.02f", b6), cut_p(p6))
S6 <- paste0("(", sprintf("%.02f", se6), ")")
SD6 <- sprintf("%.01f", sd6)

tab <- paste0("
  \\begin{table}[t] \\footnotesize
  \\begin{center}
  \\caption{Regression of Moderate Message on Extremist Message}
  \\label{tab:seq-message-model} \\vspace{1em}
  \\begin{threeparttable}
  \\begin{tabular}{lccc}  \\vspace{.1em}
  & Aligned & Opposed & Joint     \\\\
  \\hline
  Extremist Message            &$", B1[2], "$&$", B2[2], "$&$", B3[2], "$\\\\
  &$", S1[2], "$&$", S2[2], "$&$", S3[2], "$\\\\
  Target                       &$", B1[3], "$&$", B2[3], "$&$", B3[4], "$\\\\
  &$", S1[3], "$&$", S2[3], "$&$", S3[4], "$\\\\
  Opposed                      &$           $&$           $&$", B3[3], "$\\\\
  &$           $&$           $&$", S3[3], "$\\\\
  Extremist Message $\\times$ Opposed &$           $&$           $&$", B3[5],
  "$\\\\
  &$           $&$           $&$", S3[5], "$\\\\
  Target $\\times$ Opposed            &$           $&$           $&$", B3[6],
  "$\\\\
  &$           $&$           $&$", S3[6], "$\\\\
  Intercept                    &$", B1[1], "$&$", B2[1], "$&$", B3[1], "$\\\\
  &$", S1[1], "$&$", S2[1], "$&$", S3[1], "$\\\\
  \\hline
  $n$ Observations             &$",
  nobs(seq_message_aligned_model), "$&$",
  nobs(seq_message_opposed_model), "$&$",
  nobs(seq_message_joint_model), "$\\\\
  $n$ Subjects                 &$",
  ngrps(seq_message_aligned_model)[1], "$&$",
  ngrps(seq_message_opposed_model)[1], "$&$",
  ngrps(seq_message_joint_model)[1], "$\\\\
  $n$ Sessions                 &$",
  ngrps(seq_message_aligned_model)[2], "$&$",
  ngrps(seq_message_opposed_model)[2], "$&$",
  ngrps(seq_message_joint_model)[2], "$\\\\
  \\hline
  \\emph{Error terms}          &\\multicolumn{3}{c}{\\underline{Group SD}}\\\\
  Subject                      &$", SD1[1], "$&$", SD2[1], "$&$", SD3[1], "$\\\\
  Session                      &$", SD1[2], "$&$", SD2[2], "$&$", SD3[2], "$\\\\
  Residual                     &$", SD1[3], "$&$", SD2[3], "$&$", SD3[3], "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the results of mixed effects models of the Moderate
  Sender's message on the Extremist Sender's and the Target.
  The first two models separate the Aligned and Opposed conditions, and the
  third is a joint model with interaction terms to allow comparisons of the two.
  The models also include random intercepts for
  Session and Subject to control for the panel structure of the data.
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
  }
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-seq-message-model.tex")

#   Table 6 (table-message-models-1.tex) ----
load(file = "results/message_models.RData")
b1 <- fixef(message_midpoint_single_time_model)
se1 <- diag(vcov(message_midpoint_single_time_model)) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(message_midpoint_single_time_model)) ^ .5,
  sigma(message_midpoint_single_time_model))
b2 <- fixef(message_min_single_time_model)
se2 <- diag(vcov(message_min_single_time_model)) ^ .5
z2 <- abs(b2 / se2)
p2 <- 2 * (1 - pnorm(z2))
sd2 <- c(unlist(VarCorr(message_min_single_time_model)) ^ .5,
  sigma(message_min_single_time_model))
b3 <- fixef(message_max_single_time_model)
se3 <- diag(vcov(message_max_single_time_model)) ^ .5
z3 <- abs(b3 / se3)
p3 <- 2 * (1 - pnorm(z3))
sd3 <- c(unlist(VarCorr(message_max_single_time_model)) ^ .5,
  sigma(message_max_single_time_model))
b4 <- fixef(message_midpoint_aligned_extremist_time_model)
se4 <- diag(vcov(message_midpoint_aligned_extremist_time_model)) ^ .5
z4 <- abs(b4 / se4)
p4 <- 2 * (1 - pnorm(z4))
sd4 <- c(unlist(VarCorr(message_midpoint_aligned_extremist_time_model)) ^ .5,
  sigma(message_midpoint_aligned_extremist_time_model))
b5 <- fixef(message_min_aligned_extremist_time_model)
se5 <- diag(vcov(message_min_aligned_extremist_time_model)) ^ .5
z5 <- abs(b5 / se5)
p5 <- 2 * (1 - pnorm(z5))
sd5 <- c(unlist(VarCorr(message_min_aligned_extremist_time_model)) ^ .5,
  sigma(message_min_aligned_extremist_time_model))
b6 <- fixef(message_max_aligned_extremist_time_model)
se6 <- diag(vcov(message_max_aligned_extremist_time_model)) ^ .5
z6 <- abs(b6 / se6)
p6 <- 2 * (1 - pnorm(z6))
sd6 <- c(unlist(VarCorr(message_max_aligned_extremist_time_model)) ^ .5,
  sigma(message_max_aligned_extremist_time_model))
b7 <- fixef(message_midpoint_opposed_extremist_time_model)
se7 <- diag(vcov(message_midpoint_opposed_extremist_time_model)) ^ .5
z7 <- abs(b7 / se7)
p7 <- 2 * (1 - pnorm(z7))
sd7 <- c(unlist(VarCorr(message_midpoint_opposed_extremist_time_model)) ^ .5,
  sigma(message_midpoint_opposed_extremist_time_model))
b8 <- fixef(message_min_opposed_extremist_time_model)
se8 <- diag(vcov(message_min_opposed_extremist_time_model)) ^ .5
z8 <- abs(b8 / se8)
p8 <- 2 * (1 - pnorm(z8))
sd8 <- c(unlist(VarCorr(message_min_opposed_extremist_time_model)) ^ .5,
  sigma(message_min_opposed_extremist_time_model))
b9 <- fixef(message_max_opposed_extremist_time_model)
se9 <- diag(vcov(message_max_opposed_extremist_time_model)) ^ .5
z9 <- abs(b9 / se9)
p9 <- 2 * (1 - pnorm(z9))
sd9 <- c(unlist(VarCorr(message_max_opposed_extremist_time_model)) ^ .5,
  sigma(message_max_opposed_extremist_time_model))
b4a <- fixef(message_midpoint_aligned_moderate_time_model)
se4a <- diag(vcov(message_midpoint_aligned_moderate_time_model)) ^ .5
z4a <- abs(b4a / se4a)
p4a <- 2 * (1 - pnorm(z4a))
sd4a <- c(unlist(VarCorr(message_midpoint_aligned_moderate_time_model)) ^ .5,
  sigma(message_midpoint_aligned_moderate_time_model))
b5a <- fixef(message_min_aligned_moderate_time_model)
se5a <- diag(vcov(message_min_aligned_moderate_time_model)) ^ .5
z5a <- abs(b5a / se5a)
p5a <- 2 * (1 - pnorm(z5a))
sd5a <- c(unlist(VarCorr(message_min_aligned_moderate_time_model)) ^ .5,
  sigma(message_min_aligned_moderate_time_model))
b6a <- fixef(message_max_aligned_moderate_time_model)
se6a <- diag(vcov(message_max_aligned_moderate_time_model)) ^ .5
z6a <- abs(b6a / se6a)
p6a <- 2 * (1 - pnorm(z6a))
sd6a <- c(unlist(VarCorr(message_max_aligned_moderate_time_model)) ^ .5,
  sigma(message_max_aligned_moderate_time_model))
b7a <- fixef(message_midpoint_opposed_moderate_time_model)
se7a <- diag(vcov(message_midpoint_opposed_moderate_time_model)) ^ .5
z7a <- abs(b7a / se7a)
p7a <- 2 * (1 - pnorm(z7a))
sd7a <- c(unlist(VarCorr(message_midpoint_opposed_moderate_time_model)) ^ .5,
  sigma(message_midpoint_opposed_moderate_time_model))
b8a <- fixef(message_min_opposed_moderate_time_model)
se8a <- diag(vcov(message_min_opposed_moderate_time_model)) ^ .5
z8a <- abs(b8a / se8a)
p8a <- 2 * (1 - pnorm(z8a))
sd8a <- c(unlist(VarCorr(message_min_opposed_moderate_time_model)) ^ .5,
  sigma(message_min_opposed_moderate_time_model))
b9a <- fixef(message_max_opposed_moderate_time_model)
se9a <- diag(vcov(message_max_opposed_moderate_time_model)) ^ .5
z9a <- abs(b9a / se9a)
p9a <- 2 * (1 - pnorm(z9a))
sd9a <- c(unlist(VarCorr(message_max_opposed_moderate_time_model)) ^ .5,
  sigma(message_max_opposed_moderate_time_model))
B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)
B2 <- paste0(sprintf("%.02f", b2), cut_p(p2))
S2 <- paste0("(", sprintf("%.02f", se2), ")")
SD2 <- sprintf("%.01f", sd2)
B3 <- paste0(sprintf("%.02f", b3), cut_p(p3))
S3 <- paste0("(", sprintf("%.02f", se3), ")")
SD3 <- sprintf("%.01f", sd3)
B4 <- paste0(sprintf("%.02f", b4), cut_p(p4))
S4 <- paste0("(", sprintf("%.02f", se4), ")")
SD4 <- sprintf("%.01f", sd4)
B5 <- paste0(sprintf("%.02f", b5), cut_p(p5))
S5 <- paste0("(", sprintf("%.02f", se5), ")")
SD5 <- sprintf("%.01f", sd5)
B6 <- paste0(sprintf("%.02f", b6), cut_p(p6))
S6 <- paste0("(", sprintf("%.02f", se6), ")")
SD6 <- sprintf("%.01f", sd6)
B7 <- paste0(sprintf("%.02f", b7), cut_p(p7))
S7 <- paste0("(", sprintf("%.02f", se7), ")")
SD7 <- sprintf("%.01f", sd7)
B8 <- paste0(sprintf("%.02f", b8), cut_p(p8))
S8 <- paste0("(", sprintf("%.02f", se8), ")")
SD8 <- sprintf("%.01f", sd8)
B9 <- paste0(sprintf("%.02f", b9), cut_p(p9))
S9 <- paste0("(", sprintf("%.02f", se9), ")")
SD9 <- sprintf("%.01f", sd9)
B4a <- paste0(sprintf("%.02f", b4a), cut_p(p4a))
S4a <- paste0("(", sprintf("%.02f", se4a), ")")
SD4a <- sprintf("%.01f", sd4a)
B5a <- paste0(sprintf("%.02f", b5a), cut_p(p5a))
S5a <- paste0("(", sprintf("%.02f", se5a), ")")
SD5a <- sprintf("%.01f", sd5a)
B6a <- paste0(sprintf("%.02f", b6a), cut_p(p6a))
S6a <- paste0("(", sprintf("%.02f", se6a), ")")
SD6a <- sprintf("%.01f", sd6a)
B7a <- paste0(sprintf("%.02f", b7a), cut_p(p7a))
S7a <- paste0("(", sprintf("%.02f", se7a), ")")
SD7a <- sprintf("%.01f", sd7a)
B8a <- paste0(sprintf("%.02f", b8a), cut_p(p8a))
S8a <- paste0("(", sprintf("%.02f", se8a), ")")
SD8a <- sprintf("%.01f", sd8a)
B9a <- paste0(sprintf("%.02f", b9a), cut_p(p9a))
S9a <- paste0("(", sprintf("%.02f", se9a), ")")
SD9a <- sprintf("%.01f", sd9a)
tab <- paste0("
  \\begin{table}[!t]
  \\begin{center}
  \\caption{Message Models over Time}
  \\label{tab:message-model-1} \\vspace{1em}
  \\scalebox{1}{
  \\begin{threeparttable}
  \\footnotesize
  \\begin{tabular}{lcccccc
  }  \\vspace{.1em}
  &       &Aligned  &Opposed  &Aligned  &Opposed  \\\\
  &Single &Extremist&Extremist&Moderate &Moderate \\\\
  \\hline
  Target                       &$",
  B1[2], "$&$", B4[2], "$&$", B7[2], "$&$", B4a[4], "$&$", B7a[4],
  "$\\\\
  &$",
  S1[2], "$&$", S4[2], "$&$", S7[2], "$&$", S4a[4], "$&$", S7a[4],
  "$\\\\
  Second Half                  &$",
  B1[3], "$&$", B4[3], "$&$", B7[3], "$&$", B4a[3], "$&$", B7a[3],
  "$\\\\
  &$",
  S1[3], "$&$", S4[3], "$&$", S7[3], "$&$", S4a[3], "$&$", S7a[3],
  "$\\\\
  Target $\\times$             &$",
  B1[4], "$&$", B4[4], "$&$", B7[4], "$&$", B4a[6], "$&$", B7a[6],
  "$\\\\
  \\hspace{1em}Second Half     &$",
  S1[4], "$&$", S4[4], "$&$", S7[4], "$&$", S4a[6], "$&$", S7a[6],
  "$\\\\
  Extremist Message            &
  &             &             &$", B4a[2], "$&$", B7a[2],
  "$\\\\
  &
  &             &             &$", S4a[2], "$&$", S7a[2],
  "$\\\\
  Extremist Message  $\\times$ &
  &             &             &$", B4a[5], "$&$", B7a[5],
  "$\\\\
  \\hspace{1em}Second Half     &
  &             &             &$", S4a[5], "$&$", S7a[5],
  "$\\\\
  Intercept                    &$",
  B1[1], "$&$", B4[1], "$&$", B7[1], "$&$", B4a[1], "$&$", B7a[1],
  "$\\\\
  &$",
  S1[1], "$&$", S4[1], "$&$", S7[1], "$&$", S4a[1], "$&$", S7a[1],
  "$\\\\
  \\hline
  $n$ Observations             &$",
  nobs(message_midpoint_single_time_model), "$&$",
  nobs(message_midpoint_aligned_extremist_time_model), "$&$",
  nobs(message_midpoint_opposed_extremist_time_model), "$&$",
  nobs(message_midpoint_aligned_moderate_time_model), "$&$",
  nobs(message_midpoint_opposed_moderate_time_model),
  "$\\\\
  $n$ Subjects                 &$",
  ngrps(message_midpoint_single_time_model)[1], "$&$",
  ngrps(message_midpoint_aligned_extremist_time_model)[1], "$&$",
  ngrps(message_midpoint_opposed_extremist_time_model)[1], "$&$",
  ngrps(message_midpoint_aligned_moderate_time_model)[1], "$&$",
  ngrps(message_midpoint_opposed_moderate_time_model)[1],
  "$\\\\
  $n$ Sessions                 &$",
  ngrps(message_midpoint_single_time_model)[2], "$&$",
  ngrps(message_midpoint_aligned_extremist_time_model)[2], "$&$",
  ngrps(message_midpoint_opposed_extremist_time_model)[2], "$&$",
  ngrps(message_midpoint_aligned_moderate_time_model)[2], "$&$",
  ngrps(message_midpoint_opposed_moderate_time_model)[2],
  "$\\\\
  \\hline
  \\emph{Error terms}          &\\multicolumn{3}{c}{\\underline{Group SD}}\\\\
  Subject                      &$",
  SD1[1], "$&$", SD4[1], "$&$", SD7[1], "$&$", SD4a[1], "$&$", SD7a[1],
  "$\\\\
  Session                      &$",
  SD1[2], "$&$", SD4[2], "$&$", SD7[2], "$&$", SD4a[2], "$&$", SD7a[2],
  "$\\\\
  Residual                     &$",
  SD1[3], "$&$", SD4[3], "$&$", SD7[3], "$&$", SD4a[3], "$&$", SD7a[3],
  "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the results of mixed effects models of the
  the midpoint of senders' message intervals
  on \\emph{Target}, an indicator for the
  \\emph{Second Half} of periods, and their interaction.
  Separate models are presented by sender type.
  The models also include random intercepts for
  Session and Subject to control for the panel structure of the data.
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
  }
  \\end{tablenotes}
  \\end{threeparttable}
  }
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-message-models-1.tex")

#   Table 7 (table-action-model.tex) ----
load(file = "results/action-model.RData")
b1 <- fixef(action_moderate_model)
se1 <- diag(vcov(action_moderate_model)) ^ .5
z1 <- abs(b1 / se1)
p1 <- 2 * (1 - pnorm(z1))
sd1 <- c(unlist(VarCorr(action_moderate_model)) ^ .5,
  sigma(action_moderate_model))
B1 <- paste0(sprintf("%.02f", b1), cut_p(p1))
S1 <- paste0("(", sprintf("%.02f", se1), ")")
SD1 <- sprintf("%.01f", sd1)
b2 <- fixef(action_extremist_model)
se2 <- diag(vcov(action_extremist_model)) ^ .5
z2 <- abs(b2 / se2)
p2 <- 2 * (1 - pnorm(z2))
sd2 <- c(unlist(VarCorr(action_extremist_model)) ^ .5,
  sigma(action_extremist_model))
B2 <- paste0(sprintf("%.02f", b2), cut_p(p2))
S2 <- paste0("(", sprintf("%.02f", se2), ")")
SD2 <- sprintf("%.01f", sd2)
b3 <- fixef(action_model)
se3 <- diag(vcov(action_model)) ^ .5
z3 <- abs(b3 / se3)
p3 <- 2 * (1 - pnorm(z3))
sd3 <- c(unlist(VarCorr(action_model)) ^ .5,
  sigma(action_model))
B3 <- paste0(sprintf("%.02f", b3), cut_p(p3))
S3 <- paste0("(", sprintf("%.02f", se3), ")")
SD3 <- sprintf("%.01f", sd3)
b4 <- fixef(action_first_half_model)
se4 <- diag(vcov(action_first_half_model)) ^ .5
z4 <- abs(b4 / se4)
p4 <- 2 * (1 - pnorm(z4))
sd4 <- c(unlist(VarCorr(action_first_half_model)) ^ .5,
  sigma(action_first_half_model))
B4 <- paste0(sprintf("%.02f", b4), cut_p(p4))
S4 <- paste0("(", sprintf("%.02f", se4), ")")
SD4 <- sprintf("%.01f", sd4)
b5 <- fixef(action_second_half_model)
se5 <- diag(vcov(action_second_half_model)) ^ .5
z5 <- abs(b5 / se5)
p5 <- 2 * (1 - pnorm(z5))
sd5 <- c(unlist(VarCorr(action_second_half_model)) ^ .5,
  sigma(action_second_half_model))
B5 <- paste0(sprintf("%.02f", b5), cut_p(p5))
S5 <- paste0("(", sprintf("%.02f", se5), ")")
SD5 <- sprintf("%.01f", sd5)
tab <- paste0("
  \\begin{table}[t] \\footnotesize
  \\begin{center}
  \\caption{Regressions of Actions}
  \\label{tab:action-model} \\vspace{1em}
  \\begin{threeparttable}
  \\begin{tabular}{lccccc}  \\vspace{.1em}
  & Moderate& Extremist      & Joint   & First Half & Second Half   \\\\
  \\hline
  Moderate Message                   &$", B1[2], "$&             &$",
  B3[2], "$&$", B4[2], "$&$", B5[2], "$\\\\
  &$", S1[2], "$&             &$", S3[2], "$&$", S4[2], "$&$", S5[2], "$\\\\
  Extremist Message                  &             &$", B2[2], "$&$",
  B3[3], "$&$", B4[3], "$&$", B5[3], "$\\\\
  &             &$", S2[2], "$&$", S3[3], "$&$", S4[3], "$&$", S5[3], "$\\\\
  Moderate Message $\\times$ Aligned &$", B1[5], "$&             &$",
  B3[6], "$&$", B4[6], "$&$", B5[6], "$\\\\
  &$", S1[5], "$&             &$", S3[6], "$&$", S4[6], "$&$", S5[6], "$\\\\
  Moderate Message $\\times$ Opposed &$", B1[6], "$&             &$",
  B3[7], "$&$", B4[7], "$&$", B5[7], "$\\\\
  &$", S1[6], "$&             &$", S3[7], "$&$", S4[7], "$&$", S5[7], "$\\\\
  Extremist Message $\\times$ Opposed&             &$", B2[4], "$&$",
  B3[8], "$&$", B4[8], "$&$", B5[8], "$\\\\
  &             &$", S2[4], "$&$", S3[8], "$&$", S4[8], "$&$", S5[8], "$\\\\
  Aligned                            &$", B1[3], "$&             &$",
  B3[4], "$&$", B4[4], "$&$", B5[4], "$\\\\
  &$", S1[3], "$&             &$", S3[4], "$&$", S4[4], "$&$", S5[4], "$\\\\
  Opposed                            &$", B1[4], "$&$", B2[3], "$&$",
  B3[5], "$&$", B4[5], "$&$", B5[5], "$\\\\
  &$", S1[4], "$&$", S2[3], "$&$", S3[5], "$&$", S4[5], "$&$", S5[5], "$\\\\
  Intercept                          &$", B1[1], "$&$", B2[1], "$&$",
  B3[1], "$&$", B4[1], "$&$", B5[1], "$\\\\
  &$", S1[1], "$&$", S2[1], "$&$", S3[1], "$&$", S4[1], "$&$", S5[1], "$\\\\
  \\hline
  $n$ Observations  &$",
  nobs(action_moderate_model), "$&$",
  nobs(action_extremist_model), "$&$",
  nobs(action_model), "$&$",
  nobs(action_first_half_model), "$&$",
  nobs(action_second_half_model), "$\\\\
  $n$ Subjects      &$",
  ngrps(action_moderate_model)[1], "$&$",
  ngrps(action_extremist_model)[1], "$&$",
  ngrps(action_model)[1], "$&$",
  ngrps(action_first_half_model)[1], "$&$",
  ngrps(action_second_half_model)[1], "$\\\\
  $n$ Sessions      &$",
  ngrps(action_moderate_model)[2], "$&$",
  ngrps(action_extremist_model)[2], "$&$",
  ngrps(action_model)[2], "$&$",
  ngrps(action_first_half_model)[2], "$&$",
  ngrps(action_second_half_model)[2], "$\\\\
  \\hline
  \\emph{Error terms} & \\multicolumn{5}{c}{\\underline{Group SD}}  \\\\
  Subject           &$", SD1[1], "$&$", SD2[1], "$&$", SD3[1], "$&$",
  SD4[1], "$&$", SD5[1], "$\\\\
  Session           &$", SD1[2], "$&$", SD2[2], "$&$", SD3[2], "$&$",
  SD4[2], "$&$", SD5[2], "$\\\\
  Residual          &$", SD1[3], "$&$", SD2[3], "$&$", SD3[3], "$&$",
  SD4[3], "$&$", SD5[3], "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  The table presents the mixed effects models of \\emph{Action} on
  the Moderate and Extremist Senders' Messages, separately in the first two
  columns, and joint, interacted with treatment conditions, in the third column.
  The model also includes random intercepts for
  Session, and Subject to control for the panel structure of the data.
  $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.}
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  ")
cat(tab, file = "results/table-action-model.tex")

#   Table A1 (table-reg-message-strategies.tex) ----

print_row <- function(x)
{
  x <- sprintf("%0.2f", x)
  paste0("&$", x[1], "$&$", x[2], "$&$[", x[3], ", ", x[4], "]$\\\\ \n")
}

tab4 <- paste0(
  "
  \\begin{table}[p]
  \\begin{center}
  \\caption{Model of Midpoint \\& Range}
  \\label{tab:reg-message-strategies}
  \\begin{threeparttable} \\footnotesize
  \\begin{tabular}{lccc}
  \\hline \\hline
  &Estimate& Std. Error & 95\\% CI \\\\ \\vspace{-1.5em} \\\\
  \\hline
  Midpoint Equation \\\\
  \\hline
  ",
  "Intercept",
  print_row(
    summary(sf_messages, par = "a0")$summary[c(1, 3, 4, 8)]),
  "Target",
  print_row(
    summary(sf_messages, par = "b0")$summary[c(1, 3, 4, 8)]),
  "Subject Intercept Scale",
  print_row(
    summary(sf_messages, par = "a_s_id")$summary[c(1, 3, 4, 8)]),
  "Subject Slope Scale",
  print_row(
    summary(sf_messages, par = "b_s_id")$summary[c(1, 3, 4, 8)]),
  "Error Scale",
  print_row(
    summary(sf_messages, par = "s_midpoint")$summary[c(1, 3, 4, 8)]),
  "\\hline \\hline
  log(Range) Equation \\\\
  \\hline
  ",
  "Intercept",
  print_row(
    summary(sf_messages, par = "g0")$summary[c(1, 3, 4, 8)]),
  "Target",
  print_row(
    summary(sf_messages, par = "h0")$summary[c(1, 3, 4, 8)]),
  "Subject Intercept Scale",
  print_row(
    summary(sf_messages, par = "g_s_id")$summary[c(1, 3, 4, 8)]),
  "Subject Slope Scale",
  print_row(
    summary(sf_messages, par = "h_s_id")$summary[c(1, 3, 4, 8)]),
  "Error Scale",
  print_row(
    summary(sf_messages, par = "s_logrange")$summary[c(1, 3, 4, 8)]),
  "\\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
  \\item{\\footnotesize
  $n = 2190$. This table presents the estimated model
  based on the above code, and depicted in
  Figure~\\ref{fig:message-strategies}. The constant is
  suppressed, as are the constituent terms for Moderate and
  Extremist, as the use of all conditions as interaction
  terms permits direct estimation of quantites of
  interest. The model was fitted in Stan 2.10, with four
  chains, each with 1000 warmup iterations and 1000 sampling
  iterations, after which diagnostics indicated convergence
  (e.g., $\\hat{R} \\leq 1.1$ and $n_{\\text{eff}} > 400$ for
  all parameters).
  }
  \\end{tablenotes}
  \\end{threeparttable}
  \\end{center}
  \\end{table}
  "
)
cat(paste(tab4, collapse = "\n\n"), file =
    "results/table-reg-message-strategies.tex")

#   Table A2 (table-message-models-2.tex) ----
load(file = "results/sf_messages.RData")
tab <- paste0("
  \\begin{sidewaystable}[!htbp]
  \\begin{center}
  \\caption{Message Models over Time (Min and Max)}
  \\label{tab:message-model-2} \\vspace{1em}
  \\scalebox{.9}{
  \\begin{threeparttable}
  \\footnotesize
  \\begin{tabular}{l ccccc ccccc}  \\vspace{.1em}
  %&\\multicolumn{3}{c}{\\underline{Single}}
  %&\\multicolumn{3}{c}{\\underline{Aligned Extremist}}
  %&\\multicolumn{3}{c}{\\underline{Opposed Extremist}}
  %&\\multicolumn{3}{c}{\\underline{Aligned Moderate}}
  %&\\multicolumn{3}{c}{\\underline{Opposed Moderate}}
  &\\multicolumn{2}{c}{}
  &\\multicolumn{2}{c}{Aligned}
  &\\multicolumn{2}{c}{Opposed}
  &\\multicolumn{2}{c}{Aligned}
  &\\multicolumn{2}{c}{Opposed}
  \\\\
  &\\multicolumn{2}{c}{Single}
  &\\multicolumn{2}{c}{Extremist}
  &\\multicolumn{2}{c}{Extremist}
  &\\multicolumn{2}{c}{Moderate}
  &\\multicolumn{2}{c}{Moderate}
  \\\\
  %& Midpoint
  & Min & Max
  %& Midpoint
  & Min & Max
  %& Midpoint
  & Min & Max
  %& Midpoint
  & Min & Max
  %& Midpoint
  & Min & Max
  \\\\
  \\hline
  Target                       &$",
  #B1[2], "$&$",
  B2[2], "$&$", B3[2], "$&$",
  #B4[2], "$&$",
  B5[2], "$&$", B6[2], "$&$",
  #B7[2], "$&$",
  B8[2], "$&$", B9[2], "$&$",
  #B4a[4], "$&$",
  B5a[4], "$&$", B6a[4], "$&$",
  #B7a[4], #"$&$",
  B8a[4], "$&$", B9a[4],
  "$\\\\
  &$",
  #S1[2], "$&$",
  S2[2], "$&$", S3[2], "$&$",
  #S4[2], "$&$",
  S5[2], "$&$", S6[2], "$&$",
  #S7[2], "$&$",
  S8[2], "$&$", S9[2], "$&$",
  #S4a[4], "$&$",
  S5a[4], "$&$", S6a[4], "$&$",
  #S7a[4], #"$&$",
  S8a[4], "$&$", S9a[4],
  "$\\\\
  Second Half                  &$",
  #B1[3], "$&$",
  B2[3], "$&$", B3[3], "$&$",
  #B4[3], "$&$",
  B5[3], "$&$", B6[3], "$&$",
  #B7[3], "$&$",
  B8[3], "$&$", B9[3], "$&$",
  #B4a[3], "$&$",
  B5a[3], "$&$", B6a[3], "$&$",
  #B7a[3], #"$&$",
  B8a[3], "$&$", B9a[3],
  "$\\\\
  &$",
  #S1[3], "$&$",
  S2[3], "$&$", S3[3], "$&$",
  #S4[3], "$&$",
  S5[3], "$&$", S6[3], "$&$",
  #S7[3], "$&$",
  S8[3], "$&$", S9[3], "$&$",
  #S4a[3], "$&$",
  S5a[3], "$&$", S6a[3], "$&$",
  #S7a[3], #"$&$",
  S8a[3], "$&$", S9a[3],
  "$\\\\
  Target $\\times$             &$",
  #B1[4], "$&$",
  B2[4], "$&$", B3[4], "$&$",
  #B4[4], "$&$",
  B5[4], "$&$", B6[4], "$&$",
  #B7[4], "$&$",
  B8[4], "$&$", B9[4], "$&$",
  #B4a[6], "$&$",
  B5a[6], "$&$", B6a[6], "$&$",
  #B7a[6],# "$&$",
  B8a[6], "$&$", B9a[6],
  "$\\\\
  \\hspace{1em}Second Half     &$",
  #S1[4], "$&$",
  S2[4], "$&$", S3[4], "$&$",
  #S4[4], "$&$",
  S5[4], "$&$", S6[4], "$&$",
  #S7[4], "$&$",
  S8[4], "$&$", S9[4], "$&$",
  #S4a[6], "$&$",
  S5a[6], "$&$", S6a[6], "$&$",
  #S7a[6],
  #"$&$",
  S8a[6], "$&$", S9a[6],
  "$\\\\
  Extremist Message            &
  &             &
  &             &
  &             &$",
  #B4a[2], "$&$",
  B5a[2], "$&$", B6a[2], "$&$",
  #B7a[2],
  #"$&$",
  B8a[2], "$&$", B9a[2],
  "$\\\\
  &
  &             &
  &             &
  &             &$",
  #S4a[2], "$&$",
  S5a[2], "$&$", S6a[2], "$&$",
  #S7a[2],
  #"$&$",
  S8a[2], "$&$", S9a[2],
  "$\\\\
  Extremist Message  $\\times$ &
  &             &
  &             &
  &             &$",
  #B4a[5], "$&$",
  B5a[5], "$&$", B6a[5], "$&$",
  #B7a[5],
  #"$&$",
  B8a[5], "$&$", B9a[5],
  "$\\\\
  \\hspace{1em}Second Half     &
  &             &
  &             &
  &             &$",
  #S4a[5], "$&$",
  S5a[5], "$&$", S6a[5], "$&$",
  #S7a[5],
  #"$&$",
  S8a[5], "$&$", S9a[5],
  "$\\\\
  Intercept                    &$",
  #B1[1], "$&$", #
  B2[1], "$&$", B3[1], "$&$",
  #B4[1], "$&$", #
  B5[1], "$&$", B6[1], "$&$",
  #B7[1], "$&$", #
  B8[1], "$&$", B9[1], "$&$",
  #B4a[1], "$&$", #
  B5a[1], "$&$", B6a[1], "$&$",
  #B7a[1], #"$&$",
  B8a[1], "$&$", B9a[1],
  "$\\\\
  &$",
  #S1[1], "$&$",
  S2[1], "$&$", S3[1], "$&$",
  #S4[1], "$&$",
  S5[1], "$&$", S6[1], "$&$",
  #S7[1], "$&$",
  S8[1], "$&$", S9[1], "$&$",
  #S4a[1], "$&$",
  S5a[1], "$&$", S6a[1], "$&$",
  #S7a[1], #"$&$",
  S8a[1], "$&$", S9a[1],
  "$\\\\
  \\hline
  $n$ Observations             &$",
  #nobs(message_midpoint_single_time_model), "$&$",
  nobs(message_min_single_time_model), "$&$",
  nobs(message_max_single_time_model), "$&$",
  #nobs(message_midpoint_aligned_extremist_time_model), "$&$",
  nobs(message_min_aligned_extremist_time_model), "$&$",
  nobs(message_max_aligned_extremist_time_model), "$&$",
  #nobs(message_midpoint_opposed_extremist_time_model), "$&$",
  nobs(message_min_opposed_extremist_time_model), "$&$",
  nobs(message_max_opposed_extremist_time_model), "$&$",
  #nobs(message_midpoint_aligned_moderate_time_model), "$&$",
  nobs(message_min_aligned_moderate_time_model), "$&$",
  nobs(message_max_aligned_moderate_time_model), "$&$",
  #nobs(message_midpoint_opposed_moderate_time_model),
  # "$&$",
  nobs(message_min_opposed_moderate_time_model), "$&$",
  nobs(message_max_opposed_moderate_time_model),
  "$\\\\
  $n$ Subjects                 &$",
  #ngrps(message_midpoint_single_time_model)[1], "$&$",
  ngrps(message_min_single_time_model)[1], "$&$",
  ngrps(message_max_single_time_model)[1], "$&$",
  #ngrps(message_midpoint_aligned_extremist_time_model)[1], "$&$",
  ngrps(message_min_aligned_extremist_time_model)[1], "$&$",
  ngrps(message_max_aligned_extremist_time_model)[1], "$&$",
  #ngrps(message_midpoint_opposed_extremist_time_model)[1], "$&$",
  ngrps(message_min_opposed_extremist_time_model)[1], "$&$",
  ngrps(message_max_opposed_extremist_time_model)[1], "$&$",
  #ngrps(message_midpoint_aligned_moderate_time_model)[1], "$&$",
  ngrps(message_min_aligned_moderate_time_model)[1], "$&$",
  ngrps(message_max_aligned_moderate_time_model)[1], "$&$",
  #ngrps(message_midpoint_opposed_moderate_time_model)[1],
  #"$&$",
  ngrps(message_min_opposed_moderate_time_model)[1], "$&$",
  ngrps(message_max_opposed_moderate_time_model)[1],
  "$\\\\
  $n$ Sessions                 &$",
  #ngrps(message_midpoint_single_time_model)[2], "$&$",
  ngrps(message_min_single_time_model)[2], "$&$",
  ngrps(message_max_single_time_model)[2], "$&$",
  #ngrps(message_midpoint_aligned_extremist_time_model)[2], "$&$",
  ngrps(message_min_aligned_extremist_time_model)[2], "$&$",
  ngrps(message_max_aligned_extremist_time_model)[2], "$&$",
  #ngrps(message_midpoint_opposed_extremist_time_model)[2], "$&$",
  ngrps(message_min_opposed_extremist_time_model)[2], "$&$",
  ngrps(message_max_opposed_extremist_time_model)[2], "$&$",
  #ngrps(message_midpoint_aligned_moderate_time_model)[2], "$&$",
  ngrps(message_min_aligned_moderate_time_model)[2], "$&$",
  ngrps(message_max_aligned_moderate_time_model)[2], "$&$",
  #ngrps(message_midpoint_opposed_moderate_time_model)[2], #"$&$",
  ngrps(message_min_opposed_moderate_time_model)[2], "$&$",
  ngrps(message_max_opposed_moderate_time_model)[2],
  "$\\\\
  \\hline
  \\emph{Error terms}          &\\multicolumn{10}{c}{\\underline{Group SD}}\\\\
  Subject                      &$",
  #SD1[1], "$&$",
  SD2[1], "$&$", SD3[1], "$&$",
  #SD4[1], "$&$",
  SD5[1], "$&$", SD6[1], "$&$",
  #SD7[1], "$&$",
  SD8[1], "$&$", SD9[1], "$&$",
  #SD4a[1], "$&$",
  SD5a[1], "$&$", SD6a[1], "$&$",
  #SD7a[1],
  #"$&$",
  SD8a[1], "$&$", SD9a[1],
  "$\\\\
  Session                      &$",
  #SD1[2], "$&$",
  SD2[2], "$&$", SD3[2], "$&$",
  #SD4[2], "$&$",
  SD5[2], "$&$", SD6[2], "$&$",
  #SD7[2], "$&$",
  SD8[2], "$&$", SD9[2], "$&$",
  #SD4a[2], "$&$",
  SD5a[2], "$&$", SD6a[2], "$&$",
  #SD7a[2],
  #"$&$",
  SD8a[2], "$&$", SD9a[2],
  "$\\\\
  Residual                     &$",
  #SD1[3], "$&$",
  SD2[3], "$&$", SD3[3], "$&$",
  #SD4[3], "$&$",
  SD5[3], "$&$", SD6[3], "$&$",
  #SD7[3], "$&$",
  SD8[3], "$&$", SD9[3], "$&$",
  #SD4a[3], "$&$",
  SD5a[3], "$&$", SD6a[3], "$&$",
  #SD7a[3],
  #"$&$",
  SD8a[3], "$&$", SD9a[3],
  "$\\\\
  \\hline \\hline
  \\end{tabular}
  \\begin{tablenotes}
    \\item{\\footnotesize
      The table presents the results of mixed effects models of the
      the minima and maxima of senders' message intervals
      on \\emph{Target}, an indicator for the
      \\emph{Second Half} of periods, and their interaction.
      Separate models are presented by sender type and outcome variable.
      The models also include random intercepts for
      Session and Subject to control for the panel structure of the data.
      $^{***}p<0.001$, $^{**}p<0.01$, $^*p<0.05$.
    }
    \\end{tablenotes}
    \\end{threeparttable}
  }
  \\end{center}
  \\end{sidewaystable}
")
cat(tab, file = "results/table-message-models-2.tex")
